package com.hengxinguotong.zhihuichengjian.ui.security;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.StructureAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Structure;
import com.hengxinguotong.zhihuichengjian.bean.StructureListRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.task.TaskCreateActivity;
import com.hengxinguotong.zhihuichengjian.ui.quality.QualityQuestionActivity;
import com.hengxinguotong.zhihuichengjian.ui.quality.QualityTestActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.MySelectTreeView;
import com.hengxinguotong.zhihuichengjian.widget.view.MySingleSelectTreeView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/1/18.
 */

public class StructureMenuActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_tv)
    HXTextView saveTv;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.content_rl)
    RelativeLayout contentRl;

    private static Structure structure;
    private int type; //1 质量检查界面 3日常安全检查
    private StructureAdapter adapter;
    private List<Structure> mDatas, leafs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_structure_menu);
        ButterKnife.bind(this);
        titleTv.setText("检查部位选择");
        if(leafs == null){
            leafs = new ArrayList<>();
        }
        type = getIntent().getIntExtra("type", Constants.QUALITY);
        if(type == Constants.TASK_CREAT){
            saveTv.setVisibility(View.GONE);
        }
        getStructureInfo(getResources().getString(R.string.loading));
    }

    private void getStructureInfo(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this,"constructionid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/taskDistribution/queryScheduledPlanList/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    StructureListRes structureListRes = gson.fromJson(json, StructureListRes.class);
                    if(null != structureListRes.getValue() && structureListRes.getValue().size()>0){
                        mDatas = structureListRes.getValue();
                        process();
                    }else{
                        showToast(structureListRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }

    private MySelectTreeView myTree;
    private MySingleSelectTreeView mySingleTree;
    private void process(){
        if(type == Constants.TASK_CREAT){
            mySingleTree=new MySingleSelectTreeView(this);
            mySingleTree.setDatas(mDatas);
            contentRl.addView(mySingleTree);
            mySingleTree.setOnItemClickListener(new MySingleSelectTreeView.OnItemClickListener() {
                @Override
                public void click(Structure structure) {
                    StructureMenuActivity.structure = structure;
                    leafs = mySingleTree.getSelectedDatas();
                    List<Structure> selectedStructures = recursion(mDatas);
                    Intent intent = new Intent(StructureMenuActivity.this, TaskCreateActivity.class);
                    intent.putExtra("struct", structure);
                    intent.putExtra("selectedStructures", (Serializable) selectedStructures);
                    startActivity(intent);
                }
            });
        }else{
            myTree=new MySelectTreeView(this);
            myTree.setDatas(mDatas);
            contentRl.addView(myTree);
        }
    }

    private List<Structure> recursion(List<Structure> list){
        List<Structure> newDatas = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            try {
                Structure s = list.get(i);
                Structure cs = (Structure) s.clone();
                List<Structure> datas = recursion(s.getData());
                if(leafs.contains(cs)){
                    newDatas.add(cs);
                }else{
                    if(datas.size() > 0){
                        cs.setData(datas);
                        newDatas.add(cs);
                    }
                }
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        }
        return newDatas;
    }

    @OnClick({R.id.iv_back, R.id.save_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_tv:
                if(myTree != null &&myTree.getSelectedDatas()!= null&&myTree.getSelectedDatas().size() > 0){
                    leafs = myTree.getSelectedDatas();
                    List<Structure> selectedStructures = recursion(mDatas);
                    Intent intent = new Intent();
                    if(type == Constants.QUALITY){//1 质量检查界面 2日常安全检查 3质量问题 4安全问题
                        intent.setClass(StructureMenuActivity.this, QualityTestActivity.class);
                    }else if(type == Constants.DAILY_SECURITY){
                        intent.setClass(StructureMenuActivity.this, DailySecurityTestActivity.class);
                    }else if(type == Constants.QUALITY_QUESTION){
                        intent.setClass(StructureMenuActivity.this, QualityQuestionActivity.class);
                    }else if(type == Constants.SECURITY_QUESTION){
                        intent.setClass(StructureMenuActivity.this, SecurityQuestionActivity.class);
                    }
                    intent.putExtra("selectedStructures", (Serializable) selectedStructures);
                    intent.putExtra("leafs", (Serializable) leafs);
                    startActivity(intent);
                }else{
                    showToast("请至少选择一项");
                }
                break;
        }
    }
}
